import json
import logging
import os

import aiofiles

from api_v1.offer.schemas import ItemList, ItemBase
from core.config import settings
from price_analysis.utils import letter_template as lt
from price_analysis.utils.mail_sender import send_mail

main_logger = logging.getLogger("main")


class OfferRequest:
    filename: str = "offer_request_dataset.json"
    full_path = os.path.join(settings.offer_request_path, filename)

    def __init__(self, data: list[dict]) -> None:
        self.dataset: list[dict] = data
        self.request_templates = []
        self.logger = main_logger.getChild("offer_request")

    def get_request_templates(self) -> list[dict]:
        self.request_templates = []
        for position in self.dataset:
            item_list: str = self.__prepare_item_list(position["data"])
            position["request_templates"]: str = lt.message_text.format(
                item_list=item_list
            )
            self.request_templates.append(position["request_templates"])

        self.save_dataset()
        return self.request_templates

    @staticmethod
    def __prepare_item_list(items: list[ItemBase]) -> str:
        item_list: str = ""
        for idx, item in enumerate(items, start=1):
            item_list += f"{idx}  {item['Description']}"
            item_list += f"\n      тип/марка: {item['Model']}, код: {item['Index']}, производитель: {item['Provider']}"
            item_list += f"\n      Количество: {item['Quantity']} {item['Units']}\n"
        return item_list

    def save_dataset(self):
        if not os.path.isdir(settings.offer_request_path):
            os.makedirs(settings.offer_request_path, exist_ok=True)

        with open(self.full_path, mode="w") as file:
            file.write(json.dumps(self.dataset, ensure_ascii=False, indent=4))
